import { ref,reactive } from 'vue'
import storage from '@/utils/storage'
import  {
    getAddressDataAPI,
    deleteOneAddressAPI,
    updateOneAddresAPI ,
    addAddressAPI,
    queryOneAddressAPI
} from '@/api/address'
export function useAddressData() {
    const addressList = ref([])
    const loading = ref(false)

    const addressFormData = reactive({
        id: '',
        name: '',
        phone: '',
        address: '',
        userId: '',
        provinceName: '',
        isDefault: 0
    })
    function getAddressData() {
        loading.value = true
        getAddressDataAPI().then(res => {
            addressList.value = res.map(address => {
                address.isDefault = address.isDefault === 1
                return address
            })
        }).finally(_ => {
            loading.value = false
        })
    }

    function handleDelete({ id }) {
        uni.showModal({
            content: '确定删除该地址？',
            success: async (res) => {
                if(res.confirm) {
                    await deleteOneAddressAPI({ id })
                    await getAddressData()
                    uni.showToast({ title: '删除成功',icon: 'none'})
                }
            }
        })
    }

    function handleDefault(address) {
        updateOneAddresAPI({
            id: address.id,
            isDefault: address.isDefault ? 0 : 1
        }).then(res =>{
            uni.showToast({ title: res,icon: 'none'})
            getAddressData()
        })
    }

    function submitAddress() {
        if(addressFormData.id) {
            updateOneAddresAPI(addressFormData).then(res => {
                submitAfter(res)
            })
        } else {
            addressFormData.userId = storage.get('userInfo').id
            addAddressAPI(addressFormData).then(res => {
                submitAfter(res)
            })
        }
    }

    function getOneAddress(id) {
        queryOneAddressAPI(id).then(res => {
            for (const key in addressFormData) {
                addressFormData[key] = res[key]
            }
        })
    }
    function submitAfter(res) {
        uni.showToast({ title: res,icon: 'none'})
        uni.navigateTo({ url: '/pages/address/address'})
    }
    return {
        addressList,
        getAddressData,
        loading,
        handleDelete,
        handleDefault,
        addressFormData,
        submitAddress,
        getOneAddress

    }
}
